import UseInput from '@/components/common/UseInput';
import { Slider, Popup } from '@taroify/core';
import { Video, View } from '@tarojs/components';
import {
  LikeOutlined,
  StarOutlined,
  ShareOutlined,
  CommentOutlined,
  ArrowLeft,
  SmileOutlined,
} from '@taroify/icons';
import { addUnits, formatTime } from '@/utils';
import { CustomTheme } from '@/context/ThemeContext';
import { getPaddingTop } from '@/utils/back';
import Taro from '@tarojs/taro';
import React, { useEffect, useRef, useState } from 'react';

const VideoPlayer: React.FC = () => {
  const videoRef = useRef<any>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [videoContext, setVideoContext] = useState<any>(null);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  useEffect(() => {
    if (videoRef.current) {
      const handleTimeUpdate = () => {
        setCurrentTime(videoRef.current!.currentTime);
      };
      const handleLoadedMetadata = () => {
        setDuration(videoRef.current!.duration);
      };

      videoRef.current.addEventListener('timeupdate', handleTimeUpdate);
      videoRef.current.addEventListener('loadedmetadata', handleLoadedMetadata);

      return () => {
        videoRef.current?.removeEventListener('timeupdate', handleTimeUpdate);
        videoRef.current?.removeEventListener(
          'loadedmetadata',
          handleLoadedMetadata,
        );
      };
    }
  }, []);
  useEffect(() => {
    if (process.env.TARO_ENV === 'weapp') {
      setVideoContext(Taro.createVideoContext('video', this));
    }
  }, []);

  const handleVideoToggle = () => {
    console.log(videoContext);
    console.log(videoRef.current);
    if (videoContext) {
      if (isPlaying) {
        videoContext.pause();
      } else {
        videoContext.play();
      }
      setIsPlaying(!isPlaying);
    } else if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };
  const handleSliderChange = (value: number) => {
    if (videoContext) {
      videoContext.seek(value);
    } else if (videoRef.current) {
      videoRef.current.currentTime = value;
    }
    setCurrentTime(value);
  };

  const items = [
    {
      value: 100323,
      key: 'like',
      label: '点赞',
      icon: <LikeOutlined size={22} />,
      handle() {
        console.log('like');
      },
    },
    {
      value: 100323,
      key: 'star',
      label: '收藏',
      icon: <StarOutlined size={22} />,
    },
    {
      value: 100323,
      key: 'comments',
      label: '评论',
      icon: <CommentOutlined size={22} />,
      handle() {
        setOpen(true);
      },
    },
    {
      value: 233,
      key: 'share',
      label: '分享',
      icon: <ShareOutlined size={22} />,
    },
  ];
  const [open, setOpen] = useState(false);

  return (
    <View className="relative">
      <Video
        id="video"
        ref={videoRef}
        src="https://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400"
        className="w-screen min-h-10"
        controls={false}
        showCenterPlayBtn={false}
        showFullscreenBtn={false}
        showPlayBtn={false}
      />
      <View
        className="fixed inset-0  z-1 bg-transparent"
        onClick={handleVideoToggle}
      ></View>
      <View className="fixed inset-x-0 bottom-6 px-3 text-sm z-50 grid grid-cols-1 gap-3">
        <View>向阳生活，无所畏惧</View>
        <View className="flex gap-2 items-center">
          <View>{formatTime(currentTime)}</View>
          <Slider
            value={currentTime}
            max={duration}
            onChange={handleSliderChange}
          />
          <View>{formatTime(duration)}</View>
        </View>
      </View>
      <View className="fixed bottom-20 right-4 ">
        <View className="flex justify-center items-center flex-col gap-4">
          {items.map((item, i) => (
            <View
              key={i}
              onClick={item.handle}
              className="flex gap-1 flex-col items-center"
            >
              {item.icon}
              <View className="text-xs text-[#B3B3B3]">
                {addUnits(item.value)}
              </View>
            </View>
          ))}
        </View>
      </View>
      <Popup
        open={open}
        onClose={setOpen}
        placement="bottom"
        style={{ height: '80%' }}
        rounded
      >
        <UseInput
          bgc="#333333"
          shape="circle"
          right={<SmileOutlined size={24} />}
        />
        <Popup.Close />
      </Popup>
    </View>
  );
};

function TikTok() {
  const paddingTop = getPaddingTop();
  return (
    <View
      className="bg-black flex flex-col text-white h-screen box-border relative"
      style={{ paddingTop }}
    >
      <ArrowLeft
        className="z-50"
        onClick={() => Taro.navigateBack()}
        size={24}
      />
      <View className="flex flex-grow  items-center justify-center">
        <VideoPlayer />
      </View>
    </View>
  );
}

export default () => (
  <CustomTheme>
    <TikTok />
  </CustomTheme>
);
